package com.ydl.slideviewpager.view;

import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.DrawableRes;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;


import java.util.List;

public class SlideViewPager extends RelativeLayout {

    private LinearLayout ll;
    private RelativeLayout rl;
    private View view;

    private ViewPager viewPager;

    private String focusColor="#FF0000";
    private String color="#333333";
    private float size=28;
    private int focusIndex=0;

    private Context context;
    public SlideViewPager(Context context) {
        super(context);
        this.context=context;
        initView();
    }

    public SlideViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        initView();
    }

    private int left,right;
    private void initView(){
//        LayoutInflater.from(context).inflate(R.layout.layout_view_pager,this);

        RelativeLayout relativeLayout= (RelativeLayout) getRootView();

        LinearLayout linearLayout=new LinearLayout(context);

        LayoutParams params=new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
        );
        linearLayout.setLayoutParams(params);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        relativeLayout.addView(linearLayout);

        ll=new LinearLayout(context);
        LinearLayout.LayoutParams params1=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, dip2px(context,52)
        );
        ll.setLayoutParams(params1);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        rl=new RelativeLayout(context);
        LinearLayout.LayoutParams params2=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,dip2px(context,2)
        );
        rl.setLayoutParams(params2);



        view=new View(context);
        LayoutParams params3=new LayoutParams(
                dip2px(context,40), LayoutParams.MATCH_PARENT
        );
        view.setLayoutParams(params3);
        rl.addView(view);

        viewPager=new ViewPager(context);
        LinearLayout.LayoutParams params4=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT
        );
        viewPager.setLayoutParams(params4);
        viewPager.setOverScrollMode(OVER_SCROLL_NEVER);

        linearLayout.addView(ll);
        linearLayout.addView(rl);
        linearLayout.addView(viewPager);

        /**
         * 监听发现分类的滑动情况，使分类下的横线随时移动
         *
         * */
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                View childAt = ll.getChildAt(position);
                if(childAt==null){
                    return;
                }
                left=childAt.getLeft();
                right=childAt.getRight();
                int width = childAt.getWidth();
                view.setLeft((int)(left+(width*positionOffset)));
                view.setRight((int)(right+(width*positionOffset)));

            }

            @Override
            public void onPageSelected(int position) {

                focusIndex=position;
                setTextViewColor();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        setCurrentItem(0);
    }

    //设置viewpager的适配器
    public void setAdapter(PagerAdapter adapter){
        viewPager.setAdapter(adapter);
    }

    //添加title文本
    public void setTextView(List<String> list){
        if(list!=null){
            ll.removeAllViews();
            for (int i = 0; i < list.size(); i++) {
                addTextView(list.get(i),i);
            }
        }
    }

    //设置非焦点title字体颜色
    public void setColor(String color) {
        this.color = color;
        if(ll.getChildCount()>0){
            for (int i = 0; i < ll.getChildCount(); i++) {
                if(i==focusIndex){
                    continue;
                }
                try {
                    TextView childAt = (TextView) ll.getChildAt(i);
                    childAt.setTextColor(Color.parseColor(color));
                }catch (RuntimeException e){

                }
            }
        }
    }

    //设置焦点title字体颜色
    public void setFocusColor(String focusColor) {
        this.focusColor = focusColor;
        if(ll.getChildCount()>focusIndex){
            try {
                TextView childAt = (TextView) ll.getChildAt(focusIndex);
                childAt.setTextSize(size);
            }catch (RuntimeException e){

            }
        }
    }

    //设置title字体大小
    public void setSize(float size) {
        this.size = size;
        if(ll.getChildCount()>0){
            for (int i = 0; i < ll.getChildCount(); i++) {
                try {
                    TextView childAt = (TextView) ll.getChildAt(i);
                    childAt.setTextSize(size);
                }catch (RuntimeException e){

                }
            }
        }
    }

    //设置title高度
    public void setTitleHeight(int height){
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,height
        );
        ll.setLayoutParams(params);
    }

    //设置滚动线高度
    public void setLineHeight(int height){
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,height
        );
        rl.setLayoutParams(params);
    }

    //设置滚动线颜色
    public void setLineColor(String color){
        view.setBackgroundColor(Color.parseColor(color));
    }

    //设置滚动线背景,与setLineColor(String color)效果相同。
    public void setLineResource(@DrawableRes int resid){
        view.setBackgroundResource(resid);
    }

    //添加title中的textview
    private void addTextView(String text, int n){
        LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(
                0, LinearLayout.LayoutParams.MATCH_PARENT
        );
        params.weight=1.0f;

        TextView textView=new TextView(context);
        textView.setLayoutParams(params);
        textView.setTextSize(size);
        textView.setTextColor(Color.parseColor(color));if(n==focusIndex){
            textView.setTextColor(Color.parseColor(focusColor));
        }
        textView.setText(text);
        textView.setGravity(Gravity.CENTER);

        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                viewPager.setCurrentItem(n,false);
            }
        });

        ll.addView(textView);

    }

    //设置跳转viewpager的第几个item
    public void setCurrentItem(int n){
        if(n<ll.getChildCount())
        focusIndex=n;
        viewPager.setCurrentItem(n,false);
    }

    //viewpager滚动切换item完成后更换title字体颜色
    private void setTextViewColor(){

        for (int i = 0; i < ll.getChildCount(); i++) {

            try {
                TextView childAt = (TextView) ll.getChildAt(i);
                if(i==focusIndex){
                    childAt.setTextColor(Color.parseColor(focusColor));
                }else {
                    childAt.setTextColor(Color.parseColor(color));
                }
            }catch (RuntimeException e){

            }
        }

    }

    /**
     * 因为我们初始化view一般都是在activity中的onCreate方法进行
     * 但是这个时候我们不能获取title中的textview的宽度，这时我们就不能画出滚动线的位置和宽度
     *Android为我们提供了这样的机制，利用View类中getViewTreeObserver()方法，为控件添加一个观察者，在控件绘制前进行回调，这样我么就可以获取控件绘制完成之后的宽度以及高度
     * */
    public boolean first=true;
    public void show(){
        if(ll.getChildCount()>0){
            View childAt = ll.getChildAt(focusIndex);
            if(childAt==null){
                return;
            }

            childAt.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

                @Override
                public boolean onPreDraw() {
                    if(first){
                        first=false;
                        left=childAt.getLeft();
                        right=childAt.getRight();

                        view.setRight(right);
                        view.setLeft(left);
                    }
                    return true;
                }
            });


        }
    }

    //将viewpager暴露出来，因为viewpager有很多样式设置，用户可以自行设置
    public ViewPager getViewPager() {
        return viewPager;
    }



    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale+0.5f);
    }

}
